package com.hee.erp.modules.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.hee.erp.filter.LoginContextHolder;
import com.hee.erp.modules.entity.SysUser;
import com.hee.erp.modules.entity.SysUserRemark;
import com.hee.erp.modules.mapper.SysUserRemarkMapper;
import com.hee.erp.modules.service.ISysUserRemarkService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hee.erp.modules.service.ISysUserService;
import com.hee.erp.pojo.LoginInfo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDate;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author weizehong
 * @since 2022-04-25
 */
@Service
@Transactional
public class SysUserRemarkServiceImpl extends ServiceImpl<SysUserRemarkMapper, SysUserRemark> implements ISysUserRemarkService {

    @Autowired
    ISysUserService sysUserService;

    @Override
    public List<SysUserRemark> getListByUserId(String userId) {

        LambdaQueryWrapper<SysUserRemark> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SysUserRemark::getUserId, userId);

        List<SysUserRemark> list = this.list(queryWrapper);
        setForigenKeyValue(list);

        if(list != null && list.size() == 0){
            LoginInfo loginUser = LoginContextHolder.get();
            SysUserRemark blankRemark = new SysUserRemark();
            blankRemark.setUserId(userId);
            blankRemark.setRemarkDate(LocalDate.now());
            blankRemark.setCreateUser(loginUser.getUserId());
            SysUser currentUser = sysUserService.getById(loginUser.getUserId());
            blankRemark.setCreateUserName(currentUser.getUserName());
            list.add(blankRemark);
        }
        return list;
    }

    @Override
    public void saveUserRemarkList(List<SysUserRemark> list) {
        list.forEach(item -> {
            if(StringUtils.isBlank(item.getId()) || item.getId().contains("-")){
                item.setId(null);
                this.save(item);
            }else{
                this.updateById(item);
            }
        });
    }

    private void setForigenKeyValue(List<SysUserRemark> list) {
        list.forEach(item -> {
            //设置createUserName
            SysUser createUser = sysUserService.getById(item.getCreateUser());
            item.setCreateUserName(createUser.getUserName());
        });
    }
}
